﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ComicQ.Domain.Table;
using NHibernate.Linq;

namespace RegisterService
{
    public class Service1 : IRegisterService
    {
        private IList<Member> _members;

        public int CheckUsername(string username)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                _members = session.Query<Member>().ToList();
            }

            return _members.Any(member => member.Username.Equals(username)) ? 1 : 0;
        }

        public int CheckEmail(string email)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                _members = session.Query<Member>().ToList();
            }

            return _members.Any(member => member.Email.Equals(email)) ? 1 : 0;
        }

        public int Register(Member member)
        {
            try
            {
                using (var session = NHibernateHelper.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        session.Save(member);
                        transaction.Commit();
                        return 1;
                    }
                }
            }
            catch(Exception)
            {
                return 0;
            }
        }

        public string CaptchaGenerator()
        {
            var path = Path.GetRandomFileName();
            path = path.Replace(".", "");
            return path;
        }
    }
}
